﻿using Mapster;
using Microsoft.AspNetCore.Mvc;
using PARK.Attend.Entitys.Dto.SpecialDate;
using PARK.Attend.Entitys.Entity;
using PARK.Attend.Interfaces;
using PARK.Common.Core.Manager;
using PARK.Common.Enum;
using PARK.Common.Extension;
using PARK.Common.Filter;
using PARK.Dependency;
using PARK.DynamicApiController;
using PARK.FriendlyException;
using PARK.JsonSerialization;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PARK.Attend
{
    /// <summary>
    /// 特殊日期
    /// </summary>
    [ApiDescriptionSettings(Tag = "Attend", Name = "SpecialDate", Order = 200)]
    [Route("api/Attend/[controller]")]
    public class SpecialDateService : ISpecialDateService, IDynamicApiController, ITransient
    {

        private readonly ISqlSugarRepository<SpecialDateEntity> _specialdateRepository;
        private readonly SqlSugarScope _db;
        private readonly IUserManager _userManager;

        public SpecialDateService(ISqlSugarRepository<SpecialDateEntity> specialdateRepository, IUserManager userManager)
        {
            _specialdateRepository = specialdateRepository;
            _db = _specialdateRepository.Context;
            _userManager = userManager;
        }

        #region Get
        /// <summary>
        /// 获取特殊日期
        /// </summary>
        /// <param name="id">参数</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            var entity = await _db.Queryable<SpecialDateEntity>().FirstAsync(p => p.id == id);
            var output = entity.Adapt<SpecialDateInfoOutput>();
            return output;
        }

        /// <summary>
		/// 获取特殊日期列表
		/// </summary>
		/// <param name="input">请求参数</param>
		/// <returns></returns>
        [HttpGet("")]
        public async Task<dynamic> GetList([FromQuery] SpecialDateListQueryInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            //日期
            List<string> queryDate = input.spdate != null ? input.spdate.Split(',').ToObeject<List<string>>() : null;
            DateTime? startdate = queryDate != null ? Ext.GetDateTime(queryDate.First()) : null;
            DateTime? enddate = queryDate != null ? Ext.GetDateTime(queryDate.Last()) : null;
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var sidx = input.sidx == null ? "id" : input.sidx;
                var data = await _db.Queryable<SpecialDateEntity>()
                    //公司权限
                    .Where(p => p.CompanyId.Equals(userInfo.companyId))
                    .Where(p => p.DeleteMark == 0)
                    .WhereIF(input.worktype != null,p => p.worktype == input.worktype)
                    //日期
                    .WhereIF(queryDate != null, a => Convert.ToDateTime(a.begspdate) >= new DateTime(startdate.ToDate().Year, startdate.ToDate().Month, startdate.ToDate().Day))
                    .WhereIF(queryDate != null, a => Convert.ToDateTime(a.begspdate) <= new DateTime(enddate.ToDate().Year, enddate.ToDate().Month, enddate.ToDate().Day))
                    .Select(it => new SpecialDateListOutput
                    {
                        id = it.id,
                        begspdate = it.begspdate,
                        endspdate = it.endspdate,
                        worktype = it.worktype,
                        description = it.description
                    }).MergeTable().OrderBy(sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
                return PageResult<SpecialDateListOutput>.SqlSugarPageResult(data);
            }
            else
                return null;
        }


        #endregion

        #region Post
        /// <summary>
        /// 新建特殊日期
        /// </summary>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task Create([FromBody] SpecialDateCrInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            try
            {
                var entity = input.Adapt<SpecialDateEntity>();
                if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
                {
                    entity.Create();
                    entity.CompanyId = userInfo.companyId;
                    entity.CompanyName = userInfo.companyName;
                    var isOk = await _db.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync();
                    if (!(isOk > 0))
                        throw PARKException.Oh(ErrorCode.COM1000);
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        /// <summary>
        /// 更新特殊日期
        /// </summary>
        /// <param name="id">主键</param>
        /// <param name="input">参数</param>
        /// <returns></returns>
        [HttpPut("{Id}")]
        public async Task Update(string Id, [FromBody] SpecialDateUpInput input)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = input.Adapt<SpecialDateEntity>();
                entity.CompanyId = userInfo.companyId;
                entity.CompanyName = userInfo.companyName;
                entity.LastModify(Id);
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1001);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task Delete(string id)
        {
            var userInfo = await _userManager.GetUserInfo();
            if (userInfo != null && userInfo.UserAdminFlag != 2 && !string.IsNullOrEmpty(userInfo.companyId))
            {
                var entity = await _db.Queryable<SpecialDateEntity>().FirstAsync(p => p.id == id);
                _ = entity ?? throw PARKException.Oh(ErrorCode.COM1005);
                entity.Delete(id);
                var isOk = await _db.Updateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                if (!(isOk > 0)) throw PARKException.Oh(ErrorCode.COM1002);
            }
            else
                throw PARKException.Bah("您的权限无法操作!");
        }

        #endregion



    }
}
